<?php
namespace app\channel\controller;
use think\Controller;
use think\Db;

class Api extends Controller
{
    private $input=[];

    private function return_json($code, $data=[]){
        $json['code'] = $code;
        if(count($data)){
            $json['data'] = $data;
        }

        echo json_encode($json);
        exit;
    }

    public function _initialize(){
        $input = input();

        if(!isset($input['channel_id']) || !isset($input['sign'])){
            $this->return_json(101); // 缺少渠道号或者渠道密钥
        }

        unset($input['sign']);

        ksort($input);
        $str='';
        foreach($input as $k=>$v){
            $str.= $k.'='.$v.'&';
        }
        $secret = model('Channel')->where('channel_id', $input['channel_id'])->value('secret');
        if(!$secret){
            $this->return_json(102); // 渠道号不存在
        }

//        $str = md5( $str . $secret );    //p($str);
//        if($str !== input('sign')){ // 27581f5c9e3a9b7fe30a42497845df83     750ef34552357ff22f9c647d0764abf0
//            $this->return_json(103); //渠道密钥错误
//        }

        $this->input = $input;
    }

    public function index(){
        $this->return_json(1);
    }

    //根据玩家信息申请
    public function player_apply(){
        if( !isset($this->input['unique_id']) || !isset($this->input['game_name']) || !isset($this->input['server_name']) || !isset($this->input['role_name'])  || !isset($this->input['pay_money']) || !isset($this->input['pay_time']) || !isset($this->input['pay_id']) || empty($this->input['unique_id']) || empty($this->input['game_name']) || empty($this->input['server_name']) || empty($this->input['role_name'])  || empty($this->input['pay_money']) || empty($this->input['pay_time']) || empty($this->input['pay_id']) ){
            $this->return_json(104); // 必填参数不能为空
        }

        if(!$endTime = strtotime($this->input['pay_time'])){
            $this->return_json(105); // 支付时间格式错误
        }

        if(!is_numeric($this->input['pay_money'])){
            $this->return_json(106); // 金额格式错误
        }

        $roleId = isset($this->input['role_id']) ? $this->input['role_id'] : '';
        $remark = isset($this->input['remark']) ? $this->input['remark'] : '';

        $save = [
            'unique_id' => $this->input['unique_id'],
            'game_name' => $this->input['game_name'],
            'server_name' => $this->input['server_name'],
            'role_name' => $this->input['role_name'],
            'role_id' => $roleId,
            'pay_money' => $this->input['pay_money'],
            'pay_time' => $endTime,
            'pay_id' => $this->input['pay_id'],
            'remark' => $remark,
            'channel_id' => $this->input['channel_id'],
            'status' => 0
        ];
        if( Db::name('ChannelRebate')->where($save)->count() ){
            $this->return_json(107); // 不能重复发送同样的返利申请信息
        }

        $save['apply_time'] = time();
        model('ChannelRebate')->save($save);

        $this->return_json(1);
    }

    //根据渠道unique_id返回结果
    public function player_apply_status(){
        if( !isset($this->input['unique_id']) || empty($this->input['unique_id']) ){
            $this->return_json(104); // 必填参数不能为空
        }
        $where['channel_id'] = $this->input['channel_id'];
        $where['unique_id'] = $this->input['unique_id'];
        $find = model('ChannelRebate')->where($where)->find();
        !$find && $this->return_json(108);

        if($find['status']==0 || $find['status']==1){
            $find['status'] = 1;
        }
        $data = [
            'unique_id' => $find['unique_id'],
            'status' => $find['status'],
            'message' => $find['message'] ? $find['message'] : '',
            'reason' => $find['reason'] ? $find['reason'] : '',
        ];

        $this->return_json(1, $data);
    }

    //根据渠道订单号申请
    public function ch_order_apply() {
        exit;
        if( !isset($this->input['data']) || empty($this->input['data']) ){
            $this->return_json(104); // 数据不能为空
        }
        $params = stripslashes(html_entity_decode($this->input['data']));
        $channelData = json_decode($params, true);

        !isset($channelData['list']) && $this->return_json(104);
        $remark = isset($channelData['remark']) ? $channelData['remark'] : '';

        $whereOrder = [];
        $channelOrder = [];
        foreach ($channelData['list'] as $k=>$v){
            if(!isset($v['unique_id']) || !isset($v['ch_order_id']) || empty($v['unique_id']) || empty($v['ch_order_id'])){
                $this->return_json(104);
            }

            if( Db::name('ChannelRebate')->where('unique_id', $v['unique_id'])->count() ){
                continue;
            }

            $chOrderId = rtrim($v['ch_order_id'], ',');
            $explodeArr = explode(',', $chOrderId);

            foreach ($explodeArr as $kk=>$vv){
                $channelOrder[$vv] = $v['unique_id'];
                $whereOrder[] = $vv;
            }
        }
        $where['ch_order_id'] = ['in', $whereOrder];
        $where['channel_id'] = $this->input['channel_id'];
        $order = Db::name('pay_order_y_'.date('Y', time()))
            ->field('channel_id,game_id,server_name,role_name,role_id,total_price,pay_time,my_order_id,ch_order_id')
            ->where($where)
            ->select();

        $insert = [];
        foreach ($order as $k=>$v){
            $insert[] = [
                'unique_id' => $channelOrder[$v['ch_order_id']],
                'channel_id' => $this->input['channel_id'],
                'game_id' => $v['game_id'],
                'server_name' => $v['server_name'],
                'role_name' => $v['role_name'],
                'role_id' => $v['role_id'],
                'pay_money' =>  $v['total_price']/100,
                'pay_time' =>  $v['pay_time'],
                'pay_id' =>  $v['my_order_id'],
                'apply_time' => time(),
                'status' => 0,
                'remark' => $remark,
            ];
        }

        Db::name('ChannelRebate')->insertAll($insert);
        $this->return_json(1); // 申请成功
    }

    //根据米娱订单号申请
    public function order_apply() {
        if( !isset($this->input['miyu_order_id']) || empty($this->input['miyu_order_id']) ){
            $this->return_json(104); // 米娱订单号不能为空
        }
        $this->input['miyu_order_id'] = rtrim($this->input['miyu_order_id'], ',');
        $remark = isset($this->input['remark']) ? $this->input['remark'] : '';

        $arr = explode(',', $this->input['miyu_order_id']);

        $str = '';
        foreach ($arr as $v) {
            $str .= "'".$v."',";
        }
        $str = rtrim($str, ',');

        $where = "my_order_id in ({$str}) && channel_id={$this->input['channel_id']}";

        $table = get_order_table($arr[0]);
        $order = Db::name($table)->field('channel_id,game_id,server_name,role_name,role_id,total_price,pay_time,my_order_id')->where($where)->select();
        if( !$order ){
            $this->return_json(108); // 该米娱订单号不存在
        }

        if(count($order)==1){
            if( $order[0]['pay_time'] == 0 ){
                $this->return_json(108); // 该米娱订单号未充值成功
            }

            $whereApply['channel_id'] = $this->input['channel_id'];
            $whereApply['game_id'] = $order[0]['game_id'];
            $whereApply['role_name'] = $order[0]['role_name'];
            $whereApply['status'] = ['<>', 3];
            $whereApply[] = ['exp', "FIND_IN_SET('{$order[0]['my_order_id']}', pay_id)"];
            if( Db::name('ChannelRebate')->where($whereApply)->count() ){
                $this->return_json(107); // 已经申请过该订单返利
            }

            Db::name('ChannelRebate')->insert([
                'channel_id' => $this->input['channel_id'],
                'game_id' => $order[0]['game_id'],
                'server_name' => $order[0]['server_name'],
                'role_name' => $order[0]['role_name'],
                'role_id' => $order[0]['role_id'],
                'pay_money' => $order[0]['total_price']/100,
                'pay_time' => $order[0]['pay_time'],
                'pay_id' => $order[0]['my_order_id'],
                'apply_time' => time(),
                'status' => 0,
                'remark' => $remark
            ]);
        }else{
            $item = [];
            foreach($order as $k=>$v){
                if( $v['pay_time'] == 0 ){
                    continue;
                }

                unset($whereApply);
                $whereApply['channel_id'] = $this->input['channel_id'];
                $whereApply['game_id'] = $v['game_id'];
                $whereApply['role_name'] = $v['role_name'];
                $whereApply['status'] = ['<>', 3];
                $whereApply[] = ['exp', "FIND_IN_SET('{$v['my_order_id']}', pay_id)"];
                if( Db::name('ChannelRebate')->where($whereApply)->count() ){
                    continue;
                }

                if(!isset($item[$this->input['channel_id']][$v['game_id']][$v['server_name']][$v['role_name']][date('Y-m-d', $v['pay_time'])])){
                    $item[$this->input['channel_id']][$v['game_id']][$v['server_name']][$v['role_name']][date('Y-m-d', $v['pay_time'])] = $v;
                }else{
                    $item[$this->input['channel_id']][$v['game_id']][$v['server_name']][$v['role_name']][date('Y-m-d', $v['pay_time'])]['total_price'] += $v['total_price'];
                    $item[$this->input['channel_id']][$v['game_id']][$v['server_name']][$v['role_name']][date('Y-m-d', $v['pay_time'])]['my_order_id'] .= ','.$v['my_order_id'];
                }
            }

            if( !count($item) ){
                $this->return_json(107);
            }

            $insert = [];
            foreach ($item as $channelId=>$v){
                foreach ($v as $gameId=>$vv){
                    foreach ($vv as $serverName=>$vvv){
                        foreach ($vvv as $roleName=>$vvvv){
                            foreach ($vvvv as $payTime=>$vvvvv){
                                $insert[] = [
                                    'channel_id' => $this->input['channel_id'],
                                    'game_id' => $vvvvv['game_id'],
                                    'server_name' => $vvvvv['server_name'],
                                    'role_name' => $vvvvv['role_name'],
                                    'role_id' => $vvvvv['role_id'],
                                    'pay_money' =>  $vvvvv['total_price']/100,
                                    'pay_time' =>  $vvvvv['pay_time'],
                                    'pay_id' =>  $vvvvv['my_order_id'],
                                    'apply_time' => time(),
                                    'status' => 0,
                                    'remark' => $remark,
                                ];
                            }
                        }
                    }
                }
            }

            Db::name('ChannelRebate')->insertAll($insert);
        }

        $this->return_json(1); // 申请成功
    }

    //获取该订单申请状态
    public function order_apply_status(){
        if( !isset($this->input['miyu_order_id']) || empty($this->input['miyu_order_id']) ){
            $this->return_json(104); // 米娱订单号不能为空
        }
        $this->input['miyu_order_id'] = rtrim($this->input['miyu_order_id'], ',');

        $arr = explode(',', $this->input['miyu_order_id']);

        $data = [];
        foreach ($arr as $k=>$v){
            unset($where);
            $where['channel_id'] = $this->input['channel_id'];
            $where[] = ['exp', "FIND_IN_SET('{$v}', pay_id)"];
            if( $find = Db::name('ChannelRebate')->where($where)->find() ){
                if($find['status']==0 || $find['status']==1){
                    $find['status'] = 1;
                }
                $data[] = [
                    'miyu_order_id' => $v,
                    'status' => $find['status'],
                    'reason' => $find['reason'],
                    'message' => $find['message']
                ];
            }
        }

        $this->return_json(1, json_encode($data));
    }

    //获取所有已申请订单
    public function applied_list() {
        $page = isset($this->input['page']) ? $this->input['page'] : 1;
        $limit = isset($this->input['limit']) ? $this->input['limit'] : 20;
        $roleName = isset($this->input['role_name']) ? $this->input['role_name'] : '';

        $where['channel_id'] = $this->input['channel_id'];
        $roleName && $where['role_name'] = ['like', "%{$roleName}%"];
        if( ! $count=Db::name('ChannelRebate')->where($where)->count() ){
            $this->return_json(1, ['list'=>[], 'count'=>0]);
        }

        $select = Db::name('ChannelRebate')
            ->where($where)
            ->limit(($page-1)*$limit, $limit)
            ->order('apply_time desc')
            ->select();

        $data = [];
        $gameIdName = model('manage/Game')->gameIdName();
        foreach ($select as $k=>$v){
            if( $v['game_id'] ){
                if( isset($gameIdName[$v['game_id']]) ){
                    $gameName = $gameIdName[$v['game_id']];
                }else{
                    $gameName = '';
                }
            }else{
                $gameName = $v['game_name'];
            }

            if($v['status']==0 || $v['status']==1){
                $v['status'] = 1;
            }

            $data[] = [
                'apply_time' => $v['apply_time'] ? date('Y-m-d H:i:s', $v['apply_time']) : '',
                'game_name' =>  $gameName,
                'server_name' => $v['server_name'],
                'role_name' => $v['role_name'],
                'role_id' => $v['role_id'],
                'pay_money' => $v['pay_money'],
                'pay_time' => $v['pay_time'] ? date('Y-m-d', $v['pay_time']) : '',
                'pay_id' => $v['pay_id'],
                'remark' => $v['remark'] ? $v['remark'] : '',
                'reason' => $v['reason'] ? $v['reason'] : '',
                'message' => $v['message'] ? $v['message'] : '',
                'status' => $v['status'],
            ];
        }
        $this->return_json(1, ['list'=>json_encode($data),'count'=>$count]);
    }
}